const app = getApp()
Page({
    data: {
        card: {
            userId: app.globalData.userInfo.id,
            avatar: '',
            name: '',
            genderOptions: ['男', '女'],
            genderIndex: 0,
            position: '',
            company: '',
            phone: '',
            email: '',
            address: '',
        }
    },

    chooseAvatar: function () {
        wx.chooseImage({
            count: 1, // 拍照或从手机相册中选1张图片
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
                this.setData({
                    'card.avatar': res.tempFilePaths[0]
                });
            }
        });
    },

    handleSave() {
        if (this.validateInputs()) {
            const app = getApp();
            const {
                avatar,
                ...formData
            } = this.data.card;
            console.log('Avatar path:', avatar);

            // 如果头像路径是本地路径，则先上传
            if (avatar.startsWith('wxfile://') || avatar.startsWith('http://tmp/')) {
                wx.uploadFile({
                    url: 'http://localhost:8080/upload/avatar', // 上传图片的接口
                    filePath: avatar,
                    name: 'file', // 上传文件的字段名
                    success: (uploadRes) => {
                        try {
                            const data = JSON.parse(uploadRes.data); // 假设返回的JSON包含图片URL
                            console.log('Upload response:', data);

                            if (data.code === 200 && data.data) {
                                console.log("data.data" + data.data);
                                this.setData({
                                    'card.avatar': '/images/personal/' + data.data
                                })
                                console.log('card.avatar: ' + this.data.card.avatar);
                                this.generateBusinessCards(); // 生成名片

                            } else {
                                wx.showToast({
                                    title: '头像上传失败',
                                    icon: 'none'
                                });
                            }
                        } catch (error) {
                            console.error('JSON解析错误:', error);
                            wx.showToast({
                                title: '头像上传失败，解析错误',
                                icon: 'none'
                            });
                        }
                    },
                    fail: (error) => {
                        console.error('头像上传失败:', error);
                        wx.showToast({
                            title: '头像上传失败，请稍后重试',
                            icon: 'none'
                        });
                    }
                });
            } else {
                // 如果头像路径已经是服务器的 URL，直接提交表单
                this.submitForm(app, formData);
            }
        }
    },

    // 请求生成名片接口
    generateBusinessCards() {
        console.log("生成名片请求开始");
        const requestData = {
            avatar: this.data.card.avatar,
            name: this.data.card.name,
            position: this.data.card.position,
            company: this.data.card.company,
            phone: this.data.card.phone,
            email: this.data.card.email,
            address: this.data.card.address
        };

        wx.request({
            url: 'http://localhost:8080/system/card/generate', // 替换为你的后端接口地址
            method: 'POST',
            data: requestData,
            header: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${wx.getStorageSync('token')}` // 如果需要带 Token
            },
            success: (res) => {
                console.log("名片生成成功", res.data);
                if (res.statusCode === 200 && res.data.message === "名片生成成功") {
                    // 获取生成的名片图片路径
                    app.globalData.hasCreatedCard = true;
                    console.log('After setting hasCreatedCard:', app.globalData.hasCreatedCard); // 打印修改后的值
                    // 把名片路径添加到名片路径的数组中
                    app.globalData.cardImagePaths.push("/images/card/" + res.data.fileName);
                    console.log(app.globalData.cardImagePaths);
                    console.log("开始上传表单数据");
                    // 上传表单数据
                    this.submitForm();
                } else {
                    // 接口返回错误信息
                    console.error('名片生成失败:', res.data.message);
                    wx.showToast({
                        title: '名片生成失败',
                        icon: 'none',
                    });
                }
            },
            fail: (err) => {
                // 请求失败
                console.error('请求失败:', err);
                wx.showToast({
                    title: '请求失败，请稍后再试',
                    icon: 'none',
                });
            }
        });
        console.log("生成名片请求结束");
    },

    submitForm: function () {
        console.log("写入数据库");
        console.log('Before setting hasCreatedCard:', app.globalData.hasCreatedCard); // 打印修改前的值
        console.log('Before setting cardImagePaths:', app.globalData.cardImagePaths); // 打印修改前的值
        if (Array.isArray(app.globalData.cardImagePaths) && app.globalData.cardImagePaths.length > 0) {
            let imagePathsString = app.globalData.cardImagePaths.join(',');
            console.log(imagePathsString); // 输出所有图片路径，以逗号分隔
            this.setData({
                'card.avatar': imagePathsString
            })
        } else {
            console.log('cardImagePaths is not an array or is empty');
        }

        console.log("this.data.card.avatar: " + this.data.card.avatar);
        console.log(this.data.card);
        app.wxRequest('POST', 'http://localhost:8080/system/card', this.data.card,
            (response) => {
                wx.navigateTo({
                  url: '/pages/index/index',
                })
            },
            (error) => {
                console.error('Request failed:', error);
                wx.showToast({
                    title: '请求失败，请稍后重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        );
        console.log("写入数据库完成");
    },


    bindNameInput: function (e) {
        this.setData({
            'card.name': e.detail.value
        }, () => {
            console.log('Updated name:', this.data.card.name);
        });
    },

    bindGenderChange: function (e) {
        console.log('Selected gender index:', e.detail.value); // 打印选中的索引
        this.setData({
            'card.genderIndex': e.detail.value
        }, () => {
            console.log('Updated genderOptions:', this.data.card.genderOptions);
        });
    },

    bindJobInput: function (e) {
        this.setData({
            'card.position': e.detail.value
        }, () => {
            console.log('Updated position:', this.data.card.position);
        });
    },

    bindCompanyInput: function (e) {
        this.setData({
            'card.company': e.detail.value
        }, () => {
            console.log('Updated company:', this.data.card.company);
        });
    },

    bindPhoneInput: function (e) {
        this.setData({
            'card.phone': e.detail.value
        }, () => {
            console.log('Updated phone:', this.data.card.phone);
        });
    },

    bindEmailInput: function (e) {
        this.setData({
            'card.email': e.detail.value
        }, () => {
            console.log('Updated email:', this.data.card.email);
        });
    },

    bindAddressInput: function (e) {
        this.setData({
            'card.address': e.detail.value
        }, () => {
            console.log('Updated address:', this.data.card.address);
        });
    },
    validateInputs: function () {
        const {
            avatar,
            name,
            position,
            company,
            phone,
            email,
            address
        } = this.data.card;

        if (!avatar) {
            wx.showToast({
                title: '请上传头像',
                icon: 'none'
            });
            return false;
        }

        if (!name.trim()) {
            wx.showToast({
                title: '请输入姓名',
                icon: 'none'
            });
            return false;
        }

        if (!position.trim()) {
            wx.showToast({
                title: '请输入曾任职务',
                icon: 'none'
            });
            return false;
        }

        if (!company.trim()) {
            wx.showToast({
                title: '请输入学校/公司',
                icon: 'none'
            });
            return false;
        }

        if (!phone.trim()) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none'
            });
            return false;
        }

        if (!email.trim()) {
            wx.showToast({
                title: '请输入邮箱',
                icon: 'none'
            });
            return false;
        }

        if (!address.trim()) {
            wx.showToast({
                title: '请输入现居地',
                icon: 'none'
            });
            return false;
        }

        return true;
    },


});